package interceptor

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"node/gin/util"
	"strings"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = http.StatusOK
		Authorization := c.Request.Header.Get(("Authorization"))
		token := strings.Split(Authorization, " ")

		if Authorization == "" {
			code = http.StatusBadRequest
		} else {
			_, err := util.ParseToken(token[0])
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					code = http.StatusBadRequest
				default:
					code = http.StatusBadRequest
				}
			}
		}
		if code != http.StatusOK {
			c.JSON(http.StatusBadRequest, map[string]interface{}{
				"code": code,
				"msg":  "权限不足",
				"data": data,
			})
			c.Abort()
		}
		c.Next()
	}
}
